package artid.com.arttogoa;

import org.apache.commons.lang3.StringUtils;

import artid.com.arttogoa.R;

import artid.com.arttogoa.barcode.Cache;
import artid.com.arttogoa.parser.AddAddressActivityParser;
import artid.com.arttogoa.parser.AddressManagementParser;
import artid.com.arttogoa.util.AlertUtils;
import artid.com.arttogoa.util.NetUtils;
import artid.com.arttogoa.util.RegexUtil;
import artid.com.arttogoa.util.ToastUtil;
import artid.com.arttogoa.view.MyEditText;
import artid.com.arttogoa.volley.VolleyBasic;
import artid.com.arttogoa.volley.VolleyCallback;
import artid.com.arttogoa.volley.VolleyData;
import artid.com.arttogoa.volley.VolleyMap;
import com.android.volley.VolleyError;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;

/**
 * 
 *    
 * 项目名称：ArtworkArtA   
 * 类名称：AddAddressActivity   
 * 类描述：添加地址页面   
 * 创建人：耿卫斌  
 * 创建时间：2016年5月16日 下午1:20:06      
 *
 */
public class AddAddressActivity extends BaseActivity implements OnClickListener {
	private Context mContext;
	private Boolean isRefresh=false;//判断是否刷新（主要用于添加新地址后通知列表刷新）
	private Boolean isEditAddress=false;//判断是否为编辑地址(默认false 添加新地址为false；修改地址为：true)
	private AddressManagementParser mAddressManagementParser;
	private MyEditText name,phone,detailedAddress;
	private TextView titleRight_tv,region,defaultAddress;
	private String is_default="0";//是否为默认地址(默认0不是默认地址 0不是，1是)
	private String address_id="",area_id="",city_id="";//地址ID/省ID/市ID
	private Boolean isAddressManagementInetnt;//是否为“地址管理”跳转过来的(默认false)
	private Boolean addressIsNull;//是否是空地址跳转过来的(默认false)
	@Override 
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_add_address);
		setContent(this, getIntent());
		mContext=AddAddressActivity.this;
		initView();
	}

	private void initView(){
		mTittle.setText("添加地址");
		setBack();
		titleRight_tv=(TextView) findViewById(R.id.title_right);
		titleRight_tv.setText("保存");
		titleRight_tv.setVisibility(View.VISIBLE);
		titleRight_tv.setOnClickListener(this);
		isEditAddress=getIntent().getBooleanExtra("isEditAddress", false);
		isAddressManagementInetnt=getIntent().getBooleanExtra("isAddressManagementInetnt", false);
		addressIsNull=getIntent().getBooleanExtra("addressIsNull", false);
		name=(MyEditText) findViewById(R.id.add_address_name);
		name.addTextChangedListener(mTextChangedListener);
		phone=(MyEditText) findViewById(R.id.add_address_phone);
		phone.addTextChangedListener(mTextChangedListener);
		region=(TextView) findViewById(R.id.add_address_region);
		region.addTextChangedListener(mTextChangedListener);
		region.setOnClickListener(this);
		detailedAddress=(MyEditText) findViewById(R.id.add_address_detailedAddress);
		detailedAddress.addTextChangedListener(mTextChangedListener);
		defaultAddress=(TextView) findViewById(R.id.add_address_defaultAddress);
		defaultAddress.setOnClickListener(this);
		titleRight_tv.setEnabled(false);
		titleRight_tv.setTextColor(Color.parseColor("#D0D0D0"));
		//这里暂时隐藏了设置默认地址UI（逻辑不删除）
		if(isEditAddress==true){
			//判断是否是编辑地址进入
			mAddressManagementParser=new AddressManagementParser();
			mAddressManagementParser=(AddressManagementParser) getIntent().getSerializableExtra("AddressManagementParser");
			if(mAddressManagementParser!=null){
				titleRight_tv.setEnabled(true);
				titleRight_tv.setTextColor(Color.parseColor("#897C5B"));
				address_id=mAddressManagementParser.getAddress_id();
				area_id=mAddressManagementParser.getArea_id();
				city_id=mAddressManagementParser.getCity_id();
				name.setText(mAddressManagementParser.getRealname());
				phone.setText(mAddressManagementParser.getMob_phone());
				region.setText(mAddressManagementParser.getAreaname()+" "+mAddressManagementParser.getCityname());
				detailedAddress.setText(mAddressManagementParser.getAddress());
				is_default=mAddressManagementParser.getIs_default();
				if("1".equals(is_default)){
					//默认
					Drawable drawable = mContext.getResources().getDrawable(R.drawable.paiz_information_select_sel2);
					drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight()); //设置边界
					defaultAddress.setCompoundDrawables(drawable,null,null, null);//画在左边
				}else{
					//非默认
					Drawable drawable = mContext.getResources().getDrawable(R.drawable.paiz_information_select_nor);
					drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight()); //设置边界
					defaultAddress.setCompoundDrawables(drawable,null,null, null);//画在左边
				}
			}
		}
		if(addressIsNull==true){
			//判断是否是发货进入增加地址
			is_default="1";
			Drawable drawable = mContext.getResources().getDrawable(R.drawable.paiz_information_select_sel2);
			drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight()); //设置边界
			defaultAddress.setCompoundDrawables(drawable,null,null, null);//画在左边
			defaultAddress.setFocusable(false);
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.title_right:
			addAndUpdataAddress();
			break;
		case R.id.add_address_region:
			//地址选择
			showSelectCityDialog();
			break;
		case R.id.add_address_defaultAddress:
			//设置默认地址
			if("1".equals(is_default)){
				//设置非默认
				is_default="0";
				Drawable drawable = mContext.getResources().getDrawable(R.drawable.paiz_information_select_nor);
				drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight()); //设置边界
				defaultAddress.setCompoundDrawables(drawable,null,null, null);//画在左边
			}else{
				//设置默认
				is_default="1";
				Drawable drawable = mContext.getResources().getDrawable(R.drawable.paiz_information_select_sel2);
				drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight()); //设置边界
				defaultAddress.setCompoundDrawables(drawable,null,null, null);//画在左边
			}
			break;
		default:
			break;
		}
	}

	/**
	 * 对EditText监听
	 */
	TextWatcher mTextChangedListener = new TextWatcher() {  
		private CharSequence temp;  
		@Override  
		public void onTextChanged(CharSequence s, int start, int before, int count) {  
			// TODO Auto-generated method stub  
			temp = s;  
		}  

		@Override  
		public void beforeTextChanged(CharSequence s, int start, int count,  
				int after) {  
			// TODO Auto-generated method stub  
			//		          mTextView.setText(s);//将输入的内容实时显示  
		}  

		@Override  
		public void afterTextChanged(Editable s) {  
			// TODO Auto-generated method stub   

			//对按钮的判断是否可用
			if(!StringUtils.isEmpty(name.getText().toString()) && RegexUtil.isMobile(phone.getText().toString()) && !StringUtils.isEmpty(detailedAddress.getText().toString()) &&
					!StringUtils.isEmpty(area_id) && !StringUtils.isEmpty(city_id)){
				titleRight_tv.setEnabled(true);
				titleRight_tv.setTextColor(Color.parseColor("#897C5B"));
			}else{
				titleRight_tv.setEnabled(false);
				titleRight_tv.setTextColor(Color.parseColor("#D0D0D0"));
			}
		}  
	};  
	
	/**
	 * 选择地址对话框
	 */
	private void showSelectCityDialog(){
		AlertUtils.CityDialog(mContext, Integer.parseInt(NetUtils.getDisplayMetrics(AddAddressActivity.this).get(NetUtils.DM_WIDTH)), new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				switch (v.getId()) {
				case R.id.pop_second_level_btnConfirm:
					//确定
					//得到省市id
					area_id= AlertUtils.getPid();
					city_id=AlertUtils.getCid();
					//省市名字
					String pname = AlertUtils.getProvName();
					String cname = AlertUtils.getCityName();
					region.setText(pname+" "+cname);
					AlertUtils.dismiss();
					break;
				case R.id.pop_second_level_btnCancel:
					//取消
					AlertUtils.dismiss();
					break;

				default:
					break;
				}
			}
		});
	}

	/**
	 * 新建/修改地址
	 *  口令	token
		名称	realname	
		手机	mob_phone	
		省id	area_id	
		地址详情	address	
		市id	city_id	
		是否默认	is_default	0不是，1是
		地址ID	address_id	空新增，有编辑
	 */
	private void addAndUpdataAddress(){
		String realname=name.getText().toString();
		String mob_phone=phone.getText().toString();
		String address=detailedAddress.getText().toString();
		VolleyBasic.getInstance((Activity)mContext).post(Cache.addAddress,
				VolleyMap.getInstance().addAddress(realname, mob_phone, area_id, address, city_id, is_default, address_id),
				AddAddressActivityParser.class, new VolleyCallback() {
			@SuppressWarnings("unchecked")
			@Override
			public void onSuccess(VolleyData vd) {
				// TODO Auto-generated method stub
				System.out.println(vd.getJson());
				AddAddressActivityParser bean=(AddAddressActivityParser) vd.getData();
				if(bean.getState()==1){
					isRefresh=true;
					Intent intent=new Intent();  
					intent.putExtra("isRefresh",isRefresh);  
					setResult(RESULT_OK, intent);
					if(isAddressManagementInetnt!=true){
						//是否为“我要发货”跳转过来的并且是添加第一条地址的就通知地址列表关闭
						Intent intent0 = new Intent("com.AddressManagement_Activity.receiver");  
						intent0.putExtra("isCloseActivity", true);
						mContext.sendBroadcast(intent0);
						Intent intent2 = new Intent("com.MyDeliverGoods_Activity.receiver");
						intent2.putExtra("addAndUpdataAddress", true);
						intent2.putExtra("address_id",bean.getAddress_id());
						intent2.putExtra("address_info", region.getText().toString()+" "+detailedAddress.getText().toString());
						mContext.sendBroadcast(intent2);
					}
					finish();
				}else{
					showToast("操作失败，请稍后重试");
				}
			}
			public void onError(VolleyError volleyError) {
				ToastUtil.toast(mContext, "网络开小差了，请重新点击设置");
			}
		});
	}
}
